package org.csu.onlineedubackend.controller;

import lombok.RequiredArgsConstructor;
import org.csu.onlineedubackend.dto.ChapterWithLessonsDTO;
import org.csu.onlineedubackend.dto.CourseCommentDTO;
import org.csu.onlineedubackend.dto.CreateCourseDTO;
import org.csu.onlineedubackend.dto.StudentProgressDTO;
import org.csu.onlineedubackend.entity.Chapter;
import org.csu.onlineedubackend.entity.Course;
import org.csu.onlineedubackend.entity.Lesson;
import org.csu.onlineedubackend.service.ChapterService;
import org.csu.onlineedubackend.service.CourseService;
import org.csu.onlineedubackend.service.LessonService;
import org.csu.onlineedubackend.service.StudentCourseService;
import org.csu.onlineedubackend.service.LogService;
import org.csu.onlineedubackend.service.UserService;
import org.csu.onlineedubackend.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;

//@CrossOrigin(origins = "http://localhost:5173") // 允许跨域
@RestController
@RequestMapping("/api/teacher/course")
@RequiredArgsConstructor
public class TeacherCourseController {

    @Autowired
    private CourseService courseService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private LessonService lessonService;
    @Autowired
    private StudentCourseService studentCourseService;
    @Autowired
    private LogService logService;
    @Autowired
    private UserService userService;
    @GetMapping("/list")
    public ResponseEntity<List<Course>> listCourses(@RequestParam Integer teacherId) {
        if (teacherId == null || teacherId <= 0) {
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok(courseService.getCoursesByTeacherId(teacherId));
    }
    //草稿箱中课程展示
    @GetMapping("/draftbox")
    public Map<String, List<Course>> getDraftBoxCourses(@RequestParam Integer teacherId) {
        return courseService.getDraftBoxCourses(teacherId);
    }
    // 获取某课程下所有学生及其观看进度
    @GetMapping("/{courseId}/students")
    public List<StudentProgressDTO> getStudentsForCourse(
            @PathVariable Integer courseId,
            @RequestParam Integer teacherId
    ) {
        return studentCourseService.getStudentsWithProgress(courseId, teacherId);
    }

    @PostMapping("/create")
    public ResponseEntity<?> createCourse(@RequestBody CreateCourseDTO createCourseDTO, HttpServletRequest request) {
        Integer courseId = courseService.createFullCourse(createCourseDTO);
        // 日志记录
        Integer teacherId = createCourseDTO.getCourse().getTeacherId();;
        User teacher = userService.getById(teacherId);
        String username = teacher != null ? teacher.getUsername() : null;
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        logService.recordTeacherCourseOperation(teacherId, username, courseId, createCourseDTO.getCourse().getTitle(), "CREATE", "创建课程", ip, userAgent);
        return ResponseEntity.ok(Map.of("courseId", courseId));
    }

    @GetMapping("/{id}")
    public Course getCourse(@PathVariable Integer id) {
        return courseService.getCourseDetailTeacher(id);
    }

    @PostMapping("/update")
    public void update(@RequestBody Course course, HttpServletRequest request) {
        courseService.updateCourse(course);
        // 日志记录
        Integer teacherId = course.getTeacherId();
        User teacher = userService.getById(teacherId);
        String username = teacher != null ? teacher.getUsername() : null;
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        logService.recordTeacherCourseOperation(teacherId, username, course.getId(), course.getTitle(), "UPDATE", "修改课程信息", ip, userAgent);
    }

    @PostMapping("/add")
    public void add(@RequestBody Course course) {
        courseService.addCourse(course);
    }

    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable Integer id, @RequestParam Integer teacherId, HttpServletRequest request) {
        // 先查后删
        Course course = courseService.getById(id);
        String courseTitle = course != null ? course.getTitle() : null;
        courseService.deleteCourseById(id);
        // 日志记录
        User teacher = userService.getById(teacherId);
        String username = teacher != null ? teacher.getUsername() : null;
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        logService.recordTeacherCourseOperation(teacherId, username, id, courseTitle, "DELETE", "删除课程", ip, userAgent);
    }

    // 获取某课程的所有章节及其课时
    @GetMapping("/{courseId}/chapters")
    public List<ChapterWithLessonsDTO> getChaptersWithLessons(@PathVariable Integer courseId) {
        return chapterService.getChaptersWithLessons(courseId);
    }

    @GetMapping("/{courseId}/comments")
    public List<CourseCommentDTO> getCommentsForCourse(
            @PathVariable Integer courseId
    ) {
       return courseService.getCommentsByCourseId(courseId);
    }

    @PostMapping("/comment/{commentId}/block")
    public ResponseEntity<String> blockComment(@PathVariable Integer commentId) {
        boolean success = courseService.blockComment(commentId);
        return success ? ResponseEntity.ok("评论已屏蔽") : ResponseEntity.status(500).body("屏蔽失败");
    }


    @PostMapping("/chapter")
    public void addChapter(@RequestBody Chapter chapter, @RequestParam Integer teacherId, HttpServletRequest request) {
        chapterService.save(chapter);
        // 日志记录
        User teacher = userService.getById(teacherId);
        String username = teacher != null ? teacher.getUsername() : null;
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        logService.recordTeacherCourseOperation(teacherId, username, chapter.getCourseId(), null, "ADD_CHAPTER", "添加章节: " + chapter.getTitle(), ip, userAgent);
    }

    @DeleteMapping("/chapter/{id}")
    public void deleteChapter(@PathVariable Integer id, @RequestParam Integer teacherId, HttpServletRequest request) {
        // 先查
        Chapter chapter = chapterService.getById(id);
        String chapterTitle = chapter != null ? chapter.getTitle() : null;
        Integer courseId = chapter != null ? chapter.getCourseId() : null;
        // 再删
        chapterService.removeById(id);
        // 日志记录
        User teacher = userService.getById(teacherId);
        String username = teacher != null ? teacher.getUsername() : null;
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        logService.recordTeacherCourseOperation(teacherId, username, courseId, null, "DELETE_CHAPTER", "删除章节: " + chapterTitle, ip, userAgent);
    }

    @PostMapping("/lesson")
    public void addLesson(@RequestBody Lesson lesson, @RequestParam Integer teacherId, @RequestParam Integer courseId, HttpServletRequest request) {
        lessonService.save(lesson);
        // 日志记录
        User teacher = userService.getById(teacherId);
        String username = teacher != null ? teacher.getUsername() : null;
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        logService.recordTeacherCourseOperation(teacherId, username, courseId, null, "ADD_LESSON", "添加课时: " + lesson.getTitle(), ip, userAgent);
    }

    @DeleteMapping("/lesson/{id}")
    public void deleteLesson(@PathVariable Integer id, @RequestParam Integer teacherId, @RequestParam Integer courseId, HttpServletRequest request) {
        Lesson lesson = lessonService.getById(id);
        String lessonTitle = lesson != null ? lesson.getTitle() : null;

        lessonService.removeById(id);
        // 日志记录
        User teacher = userService.getById(teacherId);
        String username = teacher != null ? teacher.getUsername() : null;
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        logService.recordTeacherCourseOperation(teacherId, username, courseId, null, "DELETE_LESSON", "删除课时: " + lessonTitle, ip, userAgent);
    }
}


